//
//  Comment.swift
//  Drop
//
//  Created by zhuxuhong on 2018/3/18.
//  Copyright © 2018年 zhuxuhong. All rights reserved.
//

import UIKit

class Comment: BaseObject {
    var id = 0
	var parentId = 0
    var content = ""
    var date = Date()
    var author = User()
	var toUser = User()
    var likes = 0
	var replies: [Comment] = []
	
    var isLiked = false
    var isExpanded = false
	
	lazy var attributedContent: NSAttributedString = {
		let color = UIColor.white.alpha(0.6)
		let author = NSAttributedString(string: "\(self.author.name)\n", color: color)
		let date = NSAttributedString(string: "\(self.date.shortText)\n", font: Font.p12.system, color: color, lineHeightMultiple: 1.2)
		let toUser = NSAttributedString.init(string: "@\(self.toUser.name): ", color: color)
		let content = NSAttributedString(string: self.content, font: Font.p14.boldSystem, color: .white)
		
		let attr = self.parentId == 0
			? NSMutableAttributedString(attrStrings: [author, date, content])
			: NSMutableAttributedString(attrStrings: [author, date, toUser, content])
		
		return attr
	}()
	
	override func setValue(_ value: Any?, forKey key: String) {
		if key == "date" {
			
		}
		else if key == "replies",
			let value = value as? [JSONDictionary] {
			replies = value.map{ .model(with: $0) }
		}
		else if key == "author",
			let value = value as? JSONDictionary {
			author = .model(with: value)
		}
		else if key == "toUser",
			let value = value as? JSONDictionary {
			toUser = .model(with: value)
		}
		else{
			super.setValue(value, forKey: key)
		}
	}
}

// MARK: - Sample Data
extension Comment{
	static func sampleData() -> [Comment]{
		var array: [Comment] = []
		do{
			let jsonData = try Data(contentsOf: Bundle.main.url(forResource: "comments.json", withExtension: nil)!)
			guard let json = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? JSONDictionary else{
				return array
			}
			let data = json["data"] as? [JSONDictionary] ?? []
			array = data.map{ .model(with: $0) }
		}catch{
			fatalError("JSON数据解析失败")
		}
		return array
	}
}
